package com.tlvip;

import java.util.concurrent.*;

/**
 * <p>description：</p>
 * <p>copyright： copyright(C)2016-2099</p>
 * <p>Life is short,we need passion</p>
 * <p>Summary： </p>
 * <p>instructions： </p>
 * Date 2/28/21</p>
 * Author mac
 *
 * @version 1.0
 */
public class FutureTest {
    public static void main(String[] args) throws Exception {
        String param1 = "Bird";
        String param2 = "Boat";
        FutureTask<String> future1 = new FutureTask<String>(new UseFuture(param1));
        FutureTask<String> future2 = new FutureTask<String>(new UseFuture(param2));

        ExecutorService executorService = Executors.newFixedThreadPool(2);
        //异步操作，AbstractExecutorService.submit(Runnable)启动线程池，执行Thread.start()
        //   ->FutureTask.run() ->Callable.call()
        Thread t = new Thread(future1);
        t.start();
        TimeUnit.SECONDS.sleep(2);//处理其他相关的任务。
        t.interrupt();
        future1.cancel(true);
//        executorService.submit(future1);
        executorService.submit(future2);


        System.out.println("执行中...");

        TimeUnit.SECONDS.sleep(2);//处理其他相关的任务。
        String result1 = future1.get();
        String result2 = future2.get();

        System.out.println("数据处理完成。。" + result1);
        System.out.println("数据处理完成。。" + result2);

        TimeUnit.SECONDS.sleep(5);//等待子线程处理完毕
        executorService.shutdown();


    }

    static class UseFuture implements Callable<String> {
        private String param;

        public UseFuture(String param) {
            this.param = param;
        }

        @Override
        public String call() throws Exception {
            TimeUnit.SECONDS.sleep(1);
            return param + " is ok!";
        }
    }
}
